#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUF_SIZE 64
#define NO -1

void my_close(int sockfd,int clientfd,int fd_w){

    if(sockfd > 0){
        close(sockfd);
    }
    if(clientfd > 0){
        close(clientfd);
    }
    if(fd_w > 0){
        close(fd_w);
    }

    return;
}

int my_recv(int sockfd,char* buf,int length){

    int temp=0;
    int ftemp=0;

    while(1){
        
        ftemp=recv(sockfd,buf+temp,length - temp,0);//0 阻塞(发送的缓冲区满/网络阻塞);
        if(ftemp == -1){
            perror("my_send err");
            return -1;
        }
        temp+=ftemp;
        if(ftemp == 0){
            return temp;
        }
        if(temp >= length){
            break;
        }
        
    }
    return temp;
}


int main(void){
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port =htons(8888);
    
    addr.sin_addr.s_addr=INADDR_ANY;//本地的ip都可以
    printf("IP=%s\n",inet_ntoa(addr.sin_addr));
    socklen_t addrlen= sizeof(addr);
    //绑定
    if(bind(sockfd,(struct sockaddr*)&addr,addrlen) == -1){
        perror("bind err");
        close(sockfd);
        return -1;
    }

    //监听
    if(listen(sockfd,5) == -1){
        perror("listen err");
        my_close(sockfd,NO,NO);
        return -1;
    }
    printf("waiting client connect!\n");

    //响应连接
    struct sockaddr_in client_addr;
    socklen_t clientlen;
    int clientfd=accept(sockfd,(struct sockaddr*)&client_addr,&clientlen);
    if(clientfd < 0){
        perror("accept err");
        my_close(sockfd,NO,NO);
        return -1;
    }
    printf("new connect comming\n");

    //收发数据
    int fd_w = open("./sever.txt",O_WRONLY | O_CREAT | O_TRUNC,0666);
    if(fd_w == -1){
        perror("open err");
        my_close(sockfd,clientfd,NO);
        return -1;
    }
    char buf[BUF_SIZE]={0};
    int ret=0;
    while(1){
        ret =my_recv(clientfd,buf,BUF_SIZE);
        if(ret < 0){
            perror("recv err");
            my_close(sockfd,clientfd,fd_w);
            break;
        }else if(ret > 0){

            if(write(fd_w,buf,ret) == -1){
                break;
            }
            if(ret < BUF_SIZE){
                printf("recv complete\n");
                break;
            }
            // printf("recv data:%s\n",buf);
        }else{
            printf("perr quit\n");
            break;
        }
    }


    //关闭
    my_close(sockfd,clientfd,fd_w);


    return 0;
}
